package com.p2p.system.controller;

import com.alibaba.fastjson.JSON;
import com.p2p.model.entity.Employee;
import com.p2p.model.entity.Logininfo;
import com.p2p.model.entity.Userinfo;
import com.p2p.system.common.Result;
import com.p2p.system.entity.EmailCode;
import com.p2p.system.entity.ToMail;
import com.p2p.system.exception.MyCustomerException;
import com.p2p.system.service.EmployeeService;
import com.p2p.system.service.LogininfoService;
import com.p2p.system.service.MailService;
import com.p2p.system.service.UserinfoService;
import com.p2p.system.util.JwtHelper;
import com.p2p.system.util.VerCodeGenerateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * @Date：2023/12/11
 * @Author：lyd
 */
@CrossOrigin
@RestController
@Api(tags = "邮件发送器")
@RequestMapping("/system/login")
public class EmailController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private UserinfoService userinfoService;

    @Resource
    private RedisTemplate redisTemplate;

    public  EmailController(RedisTemplate redisTemplate) {
            this.redisTemplate = redisTemplate;
        }



    private static String code;

    @Resource
    private MailService mailService;

    @ApiOperation(value = "发送邮箱验证码")
    @PostMapping("/sendEmail")
    public Result sendEmail(@RequestBody ToMail toEmail, HttpServletRequest request) {
        if(toEmail == null || toEmail.getEmail() == null ) {
            return Result.fail("参数错误!");
        }
        toEmail.setSubject("你本次的验证码是");
        // 获取验证码
        String verCode = VerCodeGenerateUtil.generateVerCode();
        code = verCode;
        redisTemplate.opsForValue().set(toEmail.getEmail(), JSON.toJSONString(verCode));
        redisTemplate.expire(toEmail.getEmail(), 5, TimeUnit.MINUTES);
        String content = "尊敬的xxx,您好:\n"
                + "\n本次请求的邮件验证码为:" + verCode + ",本验证码 5 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）";
        toEmail.setContent(content);

        Boolean check = mailService.sendTextMail(toEmail.getEmail(), toEmail.getSubject(), toEmail.getContent());
        if(check) {
            return Result.ok("发送成功");
        } else {
            return Result.fail( "发送失败");
        }
    }


    @ApiOperation(value = "员工邮箱验证码登录")
    @PostMapping("/emailLogin")
    public Result LoginByEmail(@RequestBody EmailCode emailLogin) {

        System.out.println("登录邮箱："+emailLogin.getEmail());
        if (redisTemplate.opsForValue().get(emailLogin.getEmail())==null){
            throw new MyCustomerException(219, "验证码已过期");
        }
        System.out.println("redis中的验证码："+redisTemplate.opsForValue().get(emailLogin.getEmail()));

        String code = (String) redisTemplate.opsForValue().get(emailLogin.getEmail());
        System.out.println(code);
        System.out.println("转换后的验证码"+removeQuotes(code));
        System.out.println(emailLogin.getCode());
        System.out.println(emailLogin.getCode().equals(redisTemplate.opsForValue().get(emailLogin.getEmail())));
        if (!emailLogin.getCode().equals(removeQuotes(code))){
            throw new MyCustomerException(219,"验证码不匹配");
        }
        Employee user = employeeService.getByEmail(emailLogin.getEmail());

        if (user == null){
            throw new MyCustomerException(219,"邮箱未注册");
        }



        String token = JwtHelper.createToken(user.getId().toString(), user.getEmpname(), user.getEmpphone());

        redisTemplate.delete(emailLogin.getEmail());
        return Result.ok(token);

    }


    @ApiOperation(value = "邮箱验证码登录")
    @PostMapping("/userEmailLogin")
    public Result userEmailLogin(@RequestBody EmailCode emailLogin) {

        System.out.println("登录邮箱："+emailLogin.getEmail());
        if (redisTemplate.opsForValue().get(emailLogin.getEmail())==null){
            throw new MyCustomerException(219, "验证码已过期");
        }
        System.out.println("redis中的验证码："+redisTemplate.opsForValue().get(emailLogin.getEmail()));

        String code = (String) redisTemplate.opsForValue().get(emailLogin.getEmail());
        System.out.println(code);
        System.out.println("转换后的验证码"+removeQuotes(code));
        System.out.println(emailLogin.getCode());
        System.out.println(emailLogin.getCode().equals(redisTemplate.opsForValue().get(emailLogin.getEmail())));
        if (!emailLogin.getCode().equals(removeQuotes(code))){
            throw new MyCustomerException(219,"验证码不匹配");
        }
        Userinfo user = userinfoService.getByEmail(emailLogin.getEmail());

        if (user == null){
            throw new MyCustomerException(219,"邮箱未注册");
        }



        String token = JwtHelper.createToken(user.getId().toString(), user.getRealname(), user.getPhonenumber());
        System.out.println("-------------------"+token);
        redisTemplate.delete(emailLogin.getEmail());
        return Result.ok(token);

    }

    //redis的验证码处理
    public static String removeQuotes(String str) {

        str = str.replace('"', ' ');
        str = str.trim();
        return str;
    }
}